package com.ynkj.teleprompter.view;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ynkj.teleprompter.R;
import com.ynkj.teleprompter.activity.MainActivity;
import com.ynkj.teleprompter.utiles.SharedPreferencesUtil;


public class FloatWinfowServices extends Service {

    private WindowManager winManager;
    private WindowManager.LayoutParams wmParams;
    private LayoutInflater inflater;
    //浮动布局
    private View mFloatingLayout;
    private ScrollView layout;
    private TextView textView1,textView2;
    private Button start;
    private Chronometer chronometer;
    private long rangeTime;
    private String content="";

    private long sudu=100;
    private float daxiao=15;
    private Thread myThread;
    private boolean flag=true;
    private boolean startBtn=true;
    public static final int DISPLAY_TEXT = 1;
    String displayExplainText = "";//这个是会从小到全的显示的文字
    //handler在接收到message（所含what字段为1）时，显示更新后的文字
    private Handler handler = new Handler(Looper.getMainLooper()){
        public void handleMessage(Message message){//handler接收到指令后分不同的情况对界面UI进行更新
            switch(message.what){
                case DISPLAY_TEXT:
                    textView1.setText(displayExplainText);
                    textView1.setTextColor(getResources().getColor(R.color.purple_200));
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        initWindow();
        //悬浮框点击事件的处理
        initFloating();
//        startThread();
        return new MyBinder();
    }

    public class MyBinder extends Binder {

        public FloatWinfowServices getService() {
            return FloatWinfowServices.this;
        }

    }



    @Override
    public void onCreate() {
        super.onCreate();

    }

    /**
     * 悬浮窗点击事件
     */
    private void initFloating() {
        textView2 = mFloatingLayout.findViewById(R.id.scoll_textView2);
        start = mFloatingLayout.findViewById(R.id.btn_start);
        textView1 = mFloatingLayout.findViewById(R.id.scoll_textView);
        layout = mFloatingLayout.findViewById(R.id.layout);
        //悬浮框触摸事件，设置悬浮框可拖动
        layout.setOnTouchListener(new FloatingListener());
        content=MainActivity.content;
        textView1.setText(MainActivity.content);
        textView1.setTextColor(getResources().getColor(R.color.gray));
//        textView2.setText(MainActivity.content);
        sudu= SharedPreferencesUtil.getLong(FloatWinfowServices.this,"sudu");
        daxiao=SharedPreferencesUtil.getFloat(FloatWinfowServices.this,"daxiao");
        textView1.setTextSize(daxiao);
        textView2.setTextSize(daxiao);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(startBtn){
                    startBtn=false;
                    flag=true;
                    startThread();
                }else {
                    startBtn=true;
                    flag=false;
                }

            }
        });
    }

    public void startThread(){
        //开一个字线程，让主界面中的文字逐一浮现
        myThread=new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i<content.length(); i++){
                    if(flag){
                        displayExplainText = content.substring(0, i+1);
                        try {
                            Log.e("msss","当前速度"+sudu);
                            Thread.sleep(sudu);
                            layout.post(new Runnable() {
                                public void run() {
                                    layout.fullScroll(View.FOCUS_DOWN);
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Message message = new Message();
                        message.what = DISPLAY_TEXT;
                        handler.sendMessage(message);
                    }
                }
            }
        });
        myThread.start();
    }




    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY, mStopX, mStopY;
    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private boolean isMove;

    private class FloatingListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    mStartX = (int) event.getX();
                    mStartY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mTouchCurrentX = (int) event.getRawX();
                    mTouchCurrentY = (int) event.getRawY();
                    wmParams.x += mTouchCurrentX - mTouchStartX;
                    wmParams.y += mTouchCurrentY - mTouchStartY;
                    winManager.updateViewLayout(mFloatingLayout, wmParams);
                    mTouchStartX = mTouchCurrentX;
                    mTouchStartY = mTouchCurrentY;
                    break;
                case MotionEvent.ACTION_UP:
                    mStopX = (int) event.getX();
                    mStopY = (int) event.getY();
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true;
                    }
                    break;
                default:
                    break;
            }

            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove;
        }
    }

    /**
     * 初始化窗口
     */
    private void initWindow() {
        winManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置好悬浮窗的参数
        wmParams = getParams();
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        wmParams.x = winManager.getDefaultDisplay().getWidth();
        wmParams.y = 210;
        //设置透明背景
        wmParams.format= PixelFormat.RGBA_8888;
        //得到容器，通过这个inflater来获得悬浮窗控件
        inflater = LayoutInflater.from(getApplicationContext());
        // 获取浮动窗口视图所在布局
        mFloatingLayout = inflater.inflate(R.layout.window_tc, null);
        // 添加悬浮窗的视图
        winManager.addView(mFloatingLayout, wmParams);
    }

    private WindowManager.LayoutParams getParams() {
        wmParams = new WindowManager.LayoutParams();
        //设置window type 下面变量2002是在屏幕区域显示，2003则可以显示在状态栏之上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        //设置可以显示在状态栏上
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        wmParams.height = 200;
        return wmParams;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        winManager.removeView(mFloatingLayout);
        stopThread();
    }

    public void stopThread(){
        if(myThread!=null){
            Log.e("msss","0000000000000");
//            myThread.interrupt();
            flag=false;
        }
    }
}
